import { useEffect, useState, useContext, useRef } from "react";
import styles from "./index.module.scss";
import { AudioContext } from "@/reducers/playMusic";

import { getlyric, INlyricList } from "@/api/song/index";
interface IProps {
  id: string | undefined;
}
const LyricScroll: React.FC<IProps> = (props) => {
  const lyricRef = useRef<HTMLDivElement | null>();
  const [lyricList, setlyricList] = useState<INlyricList[]>([]);
  const [Line, setLine] = useState(0);
  const { currentTime } = useContext(AudioContext);
  useEffect(() => {
    const getlyricList = () => {
      getlyric(props.id).then((res) => {
        setlyricList(res.lyricList);
      });
    };
    getlyricList();
    return () => {};
  }, [props.id]);
  useEffect(() => {
    return () => {
      const lineIndex = lyricList.findIndex((it) => {
        if (Math.floor(Number(it.time)) == Math.floor(Number(currentTime))) {
          return true;
        }
      });
      if (lineIndex > -1) {
        const scrollHeight = 25 * lineIndex;
        lyricRef.current?.scrollTo({
          top: scrollHeight < 0 ? 0 : scrollHeight,
          behavior: "smooth",
        });
        setLine(lineIndex);
      }
    };
  }, [currentTime, lyricList]);

  const style2 = {
    fontWeight: "700",
    color: "#fff",
  };

  return (
    <div className={styles.lyric}>
      <div
        className={styles.lyric_wrap}
        ref={(ref) => (lyricRef.current = ref)}
      >
        <div className={styles.lyricItem_wrap}>
          {lyricList && lyricList.length ? (
            lyricList.map((it, index) => {
              return (
                <div
                  style={index == Line ? style2 : {}}
                  className={styles.lyricItem}
                  key={index}
                  data-index={Math.floor(it.time as number)}
                >
                  {it.lyric}
                </div>
              );
            })
          ) : (
            <div>暂无歌词</div>
          )}
        </div>
      </div>
    </div>
  );
};

export default LyricScroll;
